/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.benchmark.nbntp;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Date;

import cgl.narada.service.time.ntptime.NtpConnection;
import cgl.narada.service.time.ntptime.NtpDatagramPacket;
import cgl.narada.service.time.ntptime.NtpOffset;
import cgl.narada.service.time.ntptime.NtpTimeService;
import cgl.narada.service.time.ntptime.NtpTimestamp;
import cgl.narada.service.time.ntptime.TimeServiceImpl;

/**
 * Runs as server and provides adjusted time value. This class should be used
 * when testing the client discrepancy.
 * @author Hasan Bulut  - hbulut@indiana.edu
 */
public class NtpServer extends Thread {
  //~ Instance fields ----------------------------------------------------------

  private DatagramSocket server;
  private NtpTimestamp   originateTS = new NtpTimestamp();
  private NtpTimestamp   receiveTS   = new NtpTimestamp();
  private NtpTimestamp   transmitTS  = new NtpTimestamp();
  private int            port        = 6123;

  //~ Constructors -------------------------------------------------------------

  /**
   * Generates a new NtpServer object.
   */
  public NtpServer() {
  }

  /**
   * Generates a new NtpServer object.
   *
   * @param port1 int - server port number
   */
  public NtpServer(int port1) {
    port = port1;
  }

  //~ Methods ------------------------------------------------------------------

  /**
   * Sets buffer entries from start to end-1 with the given data array
   *
   * @param start int - start value
   * @param end int - end value
   * @param tbuffer byte[] - buffer
   * @param data byte[] - data array to be copied
   */
  public void setBuffer(int start, int end, byte[] tbuffer, byte[] data) {
    if (tbuffer.length >= end) {
      for (int i = start; i < end; i++) {
        tbuffer[i] = data[i - start];
      }
    }
  }

  /**
   * MAin class
   *
   * @param argv int - port number
   *
   * @throws Exception
   */
  public static void main(String[] argv) throws Exception {
    int port = 6123; // milliseconds
    if (argv.length == 1) {
      port = Integer.parseInt(argv[0]);
      if (port < 1025 || port > 60000) {
        port = 6123;
      }
    }
    NtpTimeService ntpService = NtpTimeService.getInstance();
    NtpServer      ntpServer = new NtpServer(port);
    System.out.println("NTP Server is started");
    ntpServer.start();
    System.out.println("NTP Time Service is started");
    ntpService.start();
  }

  /**
   * Run method
   */
  public void run() {
    TimeServiceImpl tsi = TimeServiceImpl.getInstance();
    try {
      server = new DatagramSocket(port);
    } catch (SocketException ex) {
    }
    while (true) {
      NtpDatagramPacket dp1 = new NtpDatagramPacket();

      //      byte [] buffer=dp1.getDatagramPacket().getData();
      try {
        NtpDatagramPacket dp2 = new NtpDatagramPacket();
        server.receive(dp2.getDatagramPacket());
        System.out.println("packet received from " +
                           dp2.getDatagramPacket().getAddress() + "\t" +
                           dp2.getDatagramPacket().getPort());
        System.out.println("offset: " + tsi.getOffset());
        // take time T2
        long offset1 = tsi.getOffset();
        receiveTS.setTimestamp(new Date((new Date()).getTime() + offset1));
        setBuffer(NtpOffset.offReceiveTimestamp,
                  NtpOffset.offTransmitTimestamp,
                  dp1.getDatagramPacket().getData(),
                  receiveTS.getTimestampData());
        dp1.getDatagramPacket().setAddress(dp2.getDatagramPacket().getAddress());
        dp1.getDatagramPacket().setPort(dp2.getDatagramPacket().getPort());
        // copy transmit to originate
        originateTS.setTimestamp(NtpOffset.offTransmitTimestamp,
                                 dp2.getDatagramPacket().getData());
        setBuffer(NtpOffset.offOriginateTimestamp,
                  NtpOffset.offReceiveTimestamp,
                  dp1.getDatagramPacket().getData(),
                  originateTS.getTimestampData());
        // take time T3
        transmitTS.setTimestamp(new Date((new Date()).getTime() + offset1));
        setBuffer(NtpOffset.offTransmitTimestamp, NtpOffset.NTPDataLength,
                  dp1.getDatagramPacket().getData(),
                  transmitTS.getTimestampData());
        NtpConnection ntpConn = new NtpConnection(dp2.getDatagramPacket()
                                                     .getAddress(),
                                                  dp2.getDatagramPacket()
                                                     .getPort());
        if (dp1.getDatagramPacket() == null) {
          System.out.println("datagram packet is null");
        } else if (dp1.getDatagramPacket().getData() == null) {
          System.out.println("buffer is null");
        }

        ntpConn.send(dp1);
      } catch (IOException ex1) {
      }
    }
  }
}
